package com.skjanyou.applicationcase.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.geom.Area;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/***
 * 
 * 图片的加工处理，包括变大，变小，变灰。
 * expand(BufferedImage image,float resizeTimes).表示将图片放大。resizeTimes表示倍数，浮点型。
 * contract(),表示图片收缩，不带参用于上传头像压缩,带参用于聊天时图片压缩
 * pale(),图片变灰，用于用户下线时头像的变化。
 * 
 */

public abstract class ImageUtil {

	public static ImageIcon getIcon(String filePath)
	{
		return new ImageIcon((Image)getImage(filePath));
	}

	public static ImageIcon getHeadIcon(String filePath)
	{
		BufferedImage image = getImage(filePath);
		image = contract(image,69,54);
		return new ImageIcon((Image)image);

	}

	public static ImageIcon getPaleHeadIcon(String filePath)
	{
		BufferedImage image = getImage(filePath);
		image = contract(image,69,54);
		image = pale(image);
		return new ImageIcon((Image)image);

	}

	public static BufferedImage getImage(String filePath)
	{
		BufferedImage result = null;
		try {
			result = ImageIO.read(new FileInputStream(filePath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 图片放大功能
	 * @param image：所需要处理的图片流
	 * @param resizeTimes：相对于原图片的倍数，float型，大于1时为放大。
	 * @return 新的bufferedImage类型
	 */

	public static BufferedImage expand(BufferedImage image,float resizeTimes)
	{
		BufferedImage resultImage = null;
		int width = image.getWidth();
		int height = image.getHeight();

		int toWidth = (int) (width * resizeTimes);  
		int toHeight = (int) (height * resizeTimes);

		resultImage = new BufferedImage(toWidth,toHeight,BufferedImage.TYPE_INT_BGR);

		resultImage.getGraphics().drawImage(  
				image.getScaledInstance(toWidth, toHeight,  
						java.awt.Image.SCALE_SMOOTH), 0, 0, null);  
		return resultImage;
	}
	/**
	 * 图片的固定倍数0.5缩小，用于做头像
	 * @param image：用于处理的图片流
	 * @return 新的图片流
	 */

	public static BufferedImage contract(BufferedImage image)
	{
		BufferedImage resultImage = null;
		int width = image.getWidth();
		int height = image.getHeight();

		float resizeTimes = 0.5f;

		int toWidth = (int) (width * resizeTimes);  
		int toHeight = (int) (height * resizeTimes);

		resultImage = new BufferedImage(toWidth,toHeight,BufferedImage.TYPE_INT_BGR);

		resultImage.getGraphics().drawImage(  
				image.getScaledInstance(toWidth, toHeight,  
						java.awt.Image.SCALE_SMOOTH), 0, 0, null);  
		return resultImage;
	}

	/**
	 * 可以自由指定宽高的图片缩小功能，可用于聊天窗口中图片的缩小
	 * @param image：要进行处理的图片流
	 * @param toHeight：改变后的高
	 * @param toWidth：改变后的宽
	 * @return 新的图片流
	 */
	public static BufferedImage contract(BufferedImage image,int toHeight,int toWidth)
	{
		BufferedImage resultImage = null;

		resultImage = new BufferedImage(toWidth,toHeight,BufferedImage.TYPE_INT_BGR);

		resultImage.getGraphics().drawImage(  
				image.getScaledInstance(toWidth, toHeight,  
						java.awt.Image.SCALE_SMOOTH), 0, 0, null); 
		return resultImage;
	}

	/**
	 * 可以自由指定宽高的图片缩小功能，可用于聊天窗口中图片的缩小
	 * @param image：要进行处理的图片流
	 * @param toHeight：改变后的高
	 * @param toWidth：改变后的宽
	 * @param 以指定编码进行编码
	 * @return 新的图片流
	 */
	public static BufferedImage contract(BufferedImage image,int toHeight,int toWidth,int type)
	{
		BufferedImage resultImage = null;

		resultImage = new BufferedImage(toWidth,toHeight,type);

		resultImage.getGraphics().drawImage(  
				image.getScaledInstance(toWidth, toHeight,  
						java.awt.Image.SCALE_SMOOTH), 0, 0, null); 
		return resultImage;
	}

	/**
	 * 图片的灰色处理
	 * @param image：要进行处理的图片流
	 * @return 新的图片流
	 */
	public static BufferedImage pale(BufferedImage image)
	{
		int width = image.getWidth();
		int height = image.getHeight();


		BufferedImage resultImage = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
		ColorConvertOp colorConvertOp = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY),null);
		colorConvertOp.filter(image, resultImage);
		return resultImage;
	}

	/**
	 * 保存图片文件到硬盘上
	 * @param image：进行保存的图片流
	 * @param savePath：保存路径
	 * @param name：文件名字，要求以png格式保存
	 * @return 是否保存成功
	 */
	public static boolean saveImage(BufferedImage image,String savePath,String name) { 
		boolean result = true;
		try {  
			File f = new File(savePath + name);
			ImageIO.write(image,"png", f);
		} catch (Exception e) {  
			result = false;  
		}  

		return result;

	}  
	/**由字符串获得Image对象**/
	public static BufferedImage drawTranslucentStringPic(int width, int height, Font font,String drawStr)  
	{  
		try  
		{  
			BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
			Graphics2D gd = buffImg.createGraphics();  
			//设置透明  start  
			buffImg = gd.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);  
			gd=buffImg.createGraphics();  
			//设置透明  end  
			//	            gd.setFont(new Font("微软雅黑", Font.PLAIN, height)); //设置字体  
			gd.setFont(font);
			gd.setColor(Color.red); //设置颜色  
			//	            gd.drawRect(0, 0, width - 1, height - 1); //画边框  
			gd.drawString(drawStr, width/2-(height-1)*drawStr.length()/2,height - 3); //输出文字（中文横向居中）
			return buffImg;  
		} catch (Exception e) {  
			return null;  
		}  
	}  
	/**由图片过的Shape对象**/
	public static Shape getImageShape(Image img){
		ArrayList<Integer> x = new ArrayList<Integer>();
		ArrayList<Integer> y = new ArrayList<Integer>();
		int width = img.getWidth(null);
		int height = img.getHeight(null);

		PixelGrabber pgr = new PixelGrabber(img, 0, 0, -1, -1, true);
		try {
			pgr.grabPixels();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		int pixels[] =  (int[])pgr.getPixels();

		for (int i = 0;i < pixels.length;i++) {
			int alpha = getAlpha(pixels[i]);
			if(alpha == 0){
				continue;
			}else{
				x.add(i%width > 0 ? i%width-1:0);
				y.add(i%width == 0 ? (i == 0 ? 0 : i/width-1): i/width);
			}
		}

		int[][] matrix = new int[height][width];
		for(int i = 0;i < height;i++){
			for(int j = 0;j < width;j++){
				matrix[i][j] = 0;
			}
		}

		for(int c = 0;c < x.size();c++){
			matrix[y.get(c)][x.get(c)] = 1;
		}

		Area rec = new Area();
		int temp = 0;

		for(int i = 0;i < height;i++){
			for(int j = 0;j < width;j++){
				if(matrix[i][j] == 1){
					if(temp == 0){
						temp = j;
					}else if(j == width){
						if(temp == 0){
							Rectangle rectemp = new Rectangle(j,i,1,1);
							rec.add(new Area(rectemp));
						}else{
							Rectangle rectemp = new Rectangle(temp,i,j - temp,1);
							rec.add(new Area(rectemp));
							temp = 0;
						}
					}
				}else{
					if(temp != 0){
						Rectangle rectemp = new Rectangle(temp,i,j - temp,1);
						rec.add(new Area(rectemp));
						temp = 0;
					}
				}
			}
			temp = 0;
		}
		return rec;
	}

	private static int getAlpha(int pixel){
		return (pixel >> 24)&0xff;
	}
	
	
	
	
}
